package com.samson.elasticsearch.controller;

import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
import org.elasticsearch.common.unit.DistanceUnit;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.transport.client.PreBuiltTransportClient;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.net.InetAddress;

/**
 * @author samson
 * @version 1.0
 * @date 2019/7/10 16:35
 */
@RestController
@RequestMapping("/shopSearch")
public class GeoLocationShopSearchController {

    @RequestMapping("/search")
    public void search(String lat,String lng,String distance) throws Exception {
        Settings settings = Settings.builder()
                .put("cluster.name", "elasticsearch")
                .build();

        TransportClient client = new PreBuiltTransportClient(settings)
                .addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("localhost"), 9300));


        SearchResponse searchResponse = client.prepareSearch("test")
                .setTypes("doc")
                .setQuery(QueryBuilders.geoDistanceQuery("location")
                .point(Double.valueOf(lat), Double.valueOf(lng))
                .distance(distance, DistanceUnit.KILOMETERS))
                .get();

        for(SearchHit searchHit : searchResponse.getHits().getHits()) {
            System.out.println(searchHit.getSourceAsString());
        }
        client.close();
    }
}
